#-*- coding:utf-8 -*-

from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.db import connection, transaction
from django.db.utils import OperationalError
import json
import configparser
import pymysql
import time
import multiprocessing
import re
import threading
import traceback
from update.tools.w_git import Git_version
from update.tools.w_update import server_cu
from update.tools.w_deployment import deployment_zcell
from update.models import z_ioip
from conf import config

# Create your views here.

class Tohtml(object):
    def __init__(self):
        self.config_file = r'conf/config.ini'
        self.config = configparser.ConfigParser()
        self.config.read(self.config_file)
        self.mysql_con()

    def mysql_con(self):
        host = self.config.get('testmysql', 'host')
        dbname = self.config.get('testmysql', 'dbname')
        user = self.config.get('testmysql', 'username')
        pwd = self.config.get('testmysql', 'passwd')

        db = pymysql.connect(host, user, pwd, dbname, charset='utf8')
        cursor = db.cursor()
        return cursor

mysqlcon = Tohtml()
cursor = mysqlcon.mysql_con()
mycursor = connection.cursor()

def index(request):
    return render(request, 'base.html')

@csrf_exempt
def zcellup(request):
    global zcell_up_list
    #update_sql = "SELECT yic.companyId, yic.companyName, ccz.node, ccz.address FROM y_info_company AS yic, c_company_zcell_config AS ccz WHERE yic.companyId = ccz.companyId AND ccz.enabled = 1 AND yic.isUsing = 1 AND yic.isDelete = 0 AND ccz.isDelete = 0 ORDER BY yic.companyId"
    # zcell_all_sql = "select * from z_ioip"
    update_sql = "SELECT yic.companyId, yic.companyName, ccz.node, ccz.address FROM y_info_company AS yic, c_company_zcell_config AS ccz WHERE yic.companyId = ccz.companyId AND ccz.enabled = 1 AND yic.isUsing = 1 AND yic.isDelete = 0 AND ccz.isDelete = 0 AND ccz.companyId=1 ORDER BY yic.companyId"
    zcell_all_sql = "select * from tz_ioip"
    cursor.execute(update_sql)
    mycursor.execute(zcell_all_sql)
    up_data = cursor.fetchall()
    zcell_data = mycursor.fetchall()
    zcell_up_list = []
    zid = 1
    for i in up_data:
        zcell_up_json = {}
        try:
            try:
                zcell_name = [n[1] for n in zcell_data if i[3] in n].pop()
            except:
                zcell_name = ""
            zcell_up_json["id"] = zid
            zcell_up_json["companyid"] = i[0]
            zcell_up_json["companyname"] = i[1]
            zcell_up_json["zcellname"] = zcell_name
            zcell_up_json["nodename"] = i[2]
            zcell_up_json["zcellip"] = i[3]
            zid += 1
        except:
            traceback.print_exc()
        zcell_up_list.append(zcell_up_json)
    print('zcellup',zcell_up_list)
    return render(request, 'update/zcell-update.html', {"zcell_up": json.dumps(zcell_up_list)})

@csrf_exempt
def zcellde(request):
    deployment_sql = "SELECT address, count(1), count(distinct companyId) FROM c_company_zcell_config WHERE isDelete = 0 AND enabled = 1 GROUP BY address ORDER BY count(1) desc"
    company_sql = "SELECT yic.companyName, ccz.node, ccz.address FROM c_company_zcell_config AS ccz, y_info_company AS yic WHERE ccz.isDelete = 0 AND ccz.enabled = 1 AND yic.isUsing = 1 AND yic.isDelete = 0 AND yic.companyId = ccz.companyId "
    zcell_all_sql = "select * from tz_ioip"
    cursor.execute(deployment_sql)
    mycursor.execute(zcell_all_sql)
    deployment_data = cursor.fetchall()
    zcell_data = mycursor.fetchall()
    cursor.execute(company_sql)
    deployment_company = cursor.fetchall()
    zcell_de_list = []
    company_json = {}
    zid = 1
    for i in deployment_data:
        zcell_de_json = {}
        try:
            try:
                zcell_name = [n[1] for n in zcell_data if i[0] in n].pop()
            except:
                zcell_name = ""
            zcell_de_json["id"] = zid
            zcell_de_json["zcellname"] = zcell_name
            zcell_de_json["nodenumber"] = i[1]
            zcell_de_json["companynumber"] = i[2]
            zcell_de_json["zcellip"] = i[0]
            zid += 1
        except:
            traceback.print_exc()
        zcell_de_list.append(zcell_de_json)

    for m in deployment_company:
        company_one_list = []
        company_one_json = {}
        add_status = 0
        try:
            zcell_name = [n[1] for n in zcell_data if m[2] in n].pop()
        except:
            zcell_name = ""
        try:
            lists = company_json[zcell_name]
            for y in lists:
                if y["companyname"] == m[0]:
                    y["module"] = y["module"] + ',' + m[1]
                    add_status += 1
                    break
            if add_status == 0:
                company_one_json["companyname"] = m[0]
                company_one_json["module"] = m[1]
                lists.append(company_one_json)
        except:
            company_one_json["companyname"] = m[0]
            company_one_json["module"] = m[1]
            company_one_list.append(company_one_json)
            company_json[zcell_name] = company_one_list
    print('zcellde',company_json)
    print('zcellde',zcell_de_list)
    return render(request, 'update/zcell-deployment.html', {"zcell_de": json.dumps(zcell_de_list), "company_de": json.dumps(company_json)})

def zcellgit(request):
    git_module = Git_version()
    git_list = git_module.git_show()
    print()
    return render(request, 'update/zcell-git.html', { "gitdata":json.dumps(git_list)})

def zcellde_add(request,v1, v2):
    git_module = Git_version()
    git_list = git_module.git_version()
    print('zcellde_add',git_list)
    return render(request, 'update/add_deployment.html', {"zcellname":json.dumps(v1), "zcellip":json.dumps(v2), "gitmodule":json.dumps(git_list)})

def zcellgit_add(request, v1):
    return render(request, 'update/add_git.html',{"module":json.dumps(v1)})

@csrf_exempt
def updateselect(request):
    if request.is_ajax():
        if request.method == 'POST':
            companyname = eval(json.dumps(request.POST))['companyname']
            new_zcell_up_list = []
            if companyname == "":
                new_zcell_up_list = zcell_up_list
            else:
                pattern = re.compile(companyname)
                for i in zcell_up_list:
                    results = pattern.findall(i['companyname'])
                    if results != []:
                        new_zcell_up_list.append(i)
            print(new_zcell_up_list)
            return HttpResponse(json.dumps({"zcell_new_up": new_zcell_up_list}))


@csrf_exempt
def updaterequest(request):
    try:
        update_send = server_cu()
        zcell_name_sql = "select zcell from tz_ioip"
        mycursor.execute(zcell_name_sql)
        zcell_name = mycursor.fetchall()
        if request.is_ajax():
            if request.method == 'POST':
                up_data = eval(json.dumps(request.POST))
                status = int(up_data['status'])
                if status == 1:
                    up_list = []
                    for i in  zcell_name:
                        up_list.append(i[0])
                    print('updaterequest',up_list)
                    upprocess = multiprocessing.Process(target=update_send.main_body, args=(up_list, status,))
                    #p = threading.Thread(target=update_send.main_body, args=(up_list, status,))
                    upprocess.start()
                    upprocess.join()
                    print('进程返回值：%s，进程状态：%s' % (upprocess.exitcode,upprocess.is_alive))
                    #update_send.main_body(up_list,status)
                else:
                    data = up_data["data"].replace('\'','"')
                    up_list = json.loads(data)
                    if type(up_list) == type([]):
                        send_up_list = []
                        for i in up_list:
                            up_json = {}
                            module_list = []
                            old = 0
                            for n in send_up_list:
                                if n["id"] == i["zcellname"]:
                                    n["module"].append(i["nodename"])
                                    n["number"] = len(n["module"])
                                    old += 1
                                    break
                            if old == 0:
                                up_json["id"] = i["zcellname"]
                                module_list.append(i["nodename"])
                                up_json["module"] = module_list
                                up_json["number"] = len(module_list)
                                up_json["ip"] = i["zcellip"]
                                send_up_list.append(up_json)
                        print('updaterequest',send_up_list)
                        upprocess = multiprocessing.Process(target=update_send.main_body, args=(send_up_list, status,))
                        #p = threading.Thread(target=update_send.main_body, args=(send_up_list, status,))
                        upprocess.start()
                        upprocess.join()
                        print('进程返回值：%s，进程状态：%s' % (upprocess.exitcode,upprocess.is_alive))
                        #update_send.main_body(send_up_list, status)
                    else:
                        send_up_list = []
                        up_json = {}
                        module_list = []
                        up_json["id"] = up_list["zcellname"]
                        module_list.append(up_list["nodename"])
                        up_json["module"] = module_list
                        up_json["number"] = len(module_list)
                        up_json["ip"] = up_list["zcellip"]
                        send_up_list.append(up_json)
                        print('updaterequest',send_up_list)
                        upprocess = multiprocessing.Process(target=update_send.main_body, args=(send_up_list, status,))
                        #p = threading.Thread(target=update_send.main_body, args=(send_up_list, status,))
                        upprocess.start()
                        upprocess.join()
                        print('进程返回值：%s，进程状态：%s' % (upprocess.exitcode,upprocess.is_alive))
                        #update_send.main_body(send_up_list, status)
                return_status = {}
                if upprocess.exitcode == 0:
                    return_status = {"status":"更新成功"}
                elif upprocess.exitcode == 1:
                    return_status = {"status": "程序出错"}
                elif upprocess.exitcode == 2:
                    return_status = {"status": "判断异常"}
                print(return_status)
                return HttpResponse(json.dumps(return_status))
    except:
        traceback.print_exc()
        return HttpResponse()

@csrf_exempt
def deploymentrequest(request):
    deployments = deployment_zcell()
    config_file = r'conf/config.ini'
    config = configparser.ConfigParser()
    config.read(config_file)
    deployment_list = []
    if request.is_ajax():
        if request.method == 'POST':
            deployment_data = eval(json.dumps(request.POST))
            data = deployment_data["data"].replace('\'','"')
            deployment_json = json.loads(data)
            if deployment_json["configchoose"] == 'on':
                if deployment_json["modulename"][0:2] == 'AS':
                    for i in config.options('defaultconfig'):
                        rules = config.get('defaultconfig',i)
                        rule_list = rules.split('|')
                        if rule_list[0] == 'Startup.ini':
                            rule_list[2] = rule_list[2] + '=' + deployment_json["filename"] +'.exe'
                        else:
                            rule_list[2] = rule_list[2] + '=' + deployment_json["filename"]
                        deployment_json["configuration"].append(rule_list)
                else:
                    for i in config.options('defaultconfigv'):
                        rules = config.get('defaultconfigv',i)
                        rule_list = rules.split('|')
                        if rule_list[0] == 'Startup.ini':
                            rule_list[2] = rule_list[2] + '=' + deployment_json["filename"] +'.exe'
                        else:
                            rule_list[2] = rule_list[2] + '=' + deployment_json["filename"]
                        deployment_json["configuration"].append(rule_list)
            print('deploymentrequest',deployment_json)
            deployment_list.append(deployment_json)
            deprocess = multiprocessing.Process(target=deployments.deployment_threading, args=(deployment_list,))
            deprocess.start()
            deprocess.join()
            #dethread = threading.Thread(target=deployments.deployment_threading, args=(deployment_list,))
            #dethread.start()
            #print(upprocess.exitcode,upprocess.is_alive,'进程状态')
            print('进程返回值：%s，进程状态：%s' % (deprocess.exitcode,deprocess.is_alive))
            #deployments.deployment_threading(deployment_list)
            return_status = {}
            if deprocess.exitcode == 0:
                return_status = {"status": "更新成功"}
            elif deprocess.exitcode == 1:
                return_status = {"status": "程序出错"}
            elif deprocess.exitcode == 2:
                return_status = {"status": "判断异常"}
            print(return_status)
            return HttpResponse(json.dumps(return_status))

@csrf_exempt
def gitrequest(request):
    if request.is_ajax():
        if request.method == 'POST':
            git_data = eval(json.dumps(request.POST))
            data = git_data["data"].replace('\'', '"')
            git_json = json.loads(data)
            print('gitrequest',git_json)
            return HttpResponse()
